package sr.codemg.service.impl;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sr.codemg.config.JwtConfig;
import sr.codemg.config.RedisUtil;
import sr.codemg.entity.SysButtons;
import sr.codemg.mapper.SysButtonsMapper;
import sr.codemg.service.SysButtonsService;
import sr.codemg.utils.Constants;
import sr.codemg.utils.ResponseCode;
import sr.codemg.utils.StaticFunc;
import sr.codemg.vm.Base;
import sr.codemg.vm.Selects;
import sr.codemg.vm.Tables;

import java.util.List;
import java.util.Map;

/**
 * 按钮信息
 **/
@Service
public class SysButtonsServiceImpl implements SysButtonsService {

    @Autowired
    SysButtonsMapper sysButtonsMapper;

    @Autowired
    RedisUtil redisUtil;

    @Override
    public SysButtons get(String id) {
        return sysButtonsMapper.get(id);
    }

    @Override
    public Tables findList(Map<String, Object> params) {
        StaticFunc.page(params);
        List<SysButtons> data = sysButtonsMapper.findList(params);
        Integer count = sysButtonsMapper.count(params);
        return new Tables(data, count);
    }

    @Override
    public Base.Response add(SysButtons entity) {
        sysButtonsMapper.add(entity);
        return ResponseCode.getBase(Constants.SUCC);
    }

    @Override
    public Base.Response update(SysButtons entity) {
        sysButtonsMapper.update(entity);
        return ResponseCode.getBase(Constants.SUCC);
    }

    @Override
    public Base.Response delete(String id) {
        sysButtonsMapper.delete(id);
        return ResponseCode.getBase(Constants.SUCC);
    }

    @Override
    public Selects.Response select(Selects.Request req) {
        req.configPage();
        List<Selects.Select> data = sysButtonsMapper.select(req);
        Selects.Response res = new Selects.Response();
        res.setData(data);
        return res;
    }

    @Override
    public List<SysButtons> array(String menuKey, Claims claims) {
        String userId = JwtConfig.getUserId(claims);
        String roleIds = JwtConfig.getRoleId(claims);
        String key = Constants.USER_CONFIG.MENU_BUTTON + menuKey;
        List<SysButtons> data = (List<SysButtons>) redisUtil.hget(userId, key);
        if (data == null || data.size() == 0) {
            data = sysButtonsMapper.getMenuButtons(menuKey, roleIds.split(","));
            redisUtil.hset(userId, key, data);
        }
        redisUtil.expire(userId, Constants.SYS_TIMEOUT);
        return data;
    }
}

